/**
 * 
 */
package org.jim.server.demo.service;

import cn.hutool.core.util.RandomUtil;
import org.jim.core.*;
import org.jim.core.cache.redis.JedisTemplate;
import org.jim.core.exception.ImException;
import org.jim.core.packets.*;
import org.jim.core.session.id.impl.UUIDSessionIdGenerator;
import org.jim.core.utils.Md5;
import org.jim.server.JimServerAPI;
import org.jim.server.processor.login.LoginCmdProcessor;
import org.jim.server.protocol.AbstractProtocolCmdProcessor;
import org.jim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @author WChao
 *
 */
public class LoginServiceProcessor extends AbstractProtocolCmdProcessor implements LoginCmdProcessor {

	private Logger logger = LoggerFactory.getLogger(LoginServiceProcessor.class);
	
	/**
	 * 根据用户名和密码获取用户
	 * @param loginReqBody
	 * @param imChannelContext
	 * @return
	 * @author: WChao
	 */
	public User getUser(LoginReqBody loginReqBody, ImChannelContext imChannelContext) {
		User user = getUser(loginReqBody);
		return user;
	}
	/**
	 * 根据token获取用户信息
	 * @param token
	 * @return
	 * @author: WChao
	 */
	public User getUser(LoginReqBody loginReqBody) {
		String groupId = loginReqBody.getGroupId();
		String groupName = loginReqBody.getGroupName();
		String token = loginReqBody.getToken();
		JedisTemplate jedisTemplate = null;
		try {
			jedisTemplate = JedisTemplate.me();
		} catch (Exception e) {
			logger.info("连接缓存出错...."+e);
		}
		UserbasicinfoApp userbasicinfoApp = jedisTemplate.get(token, UserbasicinfoApp.class);
		if (userbasicinfoApp != null) {
			User.Builder builder = User.newBuilder()
					.userId(Integer.toString(userbasicinfoApp.getId()))
					.nick(userbasicinfoApp.getAccountName())
					.addGroup(Group.newBuilder().groupId(groupId).name(groupName).build());
			builder.avatar(userbasicinfoApp.getImage()).status(UserStatusType.ONLINE.getStatus());
			User user = builder.build();
			return user;
		}else {
			logger.info("从缓存获取userbasicinfoApp为空......");
		}
		return null;
	}
	

	/**
	 * 登陆成功返回状态码:ImStatus.C10007
	 * 登录失败返回状态码:ImStatus.C10008
	 * 注意：只要返回非成功状态码(ImStatus.C10007),其他状态码均为失败,此时用户可以自定义返回状态码，定义返回前端失败信息
	 */
	@Override
	public LoginRespBody doLogin(LoginReqBody loginReqBody, ImChannelContext imChannelContext) {
		JedisTemplate jedisTemplate = null;
		String token = loginReqBody.getToken();
		try {
			jedisTemplate = JedisTemplate.me();
		} catch (Exception e) {
			logger.info("登录失败...."+e);
			return LoginRespBody.failed();
		}
		UserbasicinfoApp userbasicinfoApp = jedisTemplate.get(token, UserbasicinfoApp.class);
		if(userbasicinfoApp != null){
			return LoginRespBody.success();
		}else {
			return LoginRespBody.failed();
		}
	}

	@Override
	public void onSuccess(User user, ImChannelContext channelContext) {
		logger.info("登录成功回调方法");
	}

	@Override
	public void onFailed(ImChannelContext imChannelContext) {
		logger.info("登录失败回调方法");
	}
}
